package com.training.admin.web.controller.projectdata;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.training.admin.entity.project.Project;
import com.training.admin.entity.project.ProjectPhase;
import com.training.admin.entity.project.ProjectPhaseCourse;
import com.training.admin.entity.project.ProjectTrainee;
import com.training.admin.entity.trainer.Trainer;
import com.training.admin.service.DataService;
import com.training.admin.service.ProjectDataService;
import com.training.admin.service.ProjectPhaseCourseService;
import com.training.admin.service.ProjectPhaseService;
import com.training.admin.service.ProjectTraineeService;

/**
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/project-data")
@MenuSetting("menu-training-project")
public class ProjectTraineeController {

	private static final Logger logger = LoggerFactory.getLogger(ProjectDataViewController.class);

	@Autowired
	private ProjectDataService projectDataService;

	@Autowired
	private ProjectPhaseService projectPhaseService;
	@Autowired
	private ProjectPhaseCourseService projectPhaseCourseService;

	@Autowired
	private ProjectTraineeService projectTraineeService;
	
	@Autowired
	@Qualifier("dataService")
	private DataService<Trainer> trainerService;

	/**
	 * 更新项目状态
	 * 
	 * @param project
	 */
	private void updateProjectStatus(Project project) {

		boolean isAllPhaseCourseAssigned = true;
		List<ProjectPhase> projectPhaseList = projectPhaseService.listByProjectId(project.getId());
		if (projectPhaseList != null) {
			for (int i = 0; i < projectPhaseList.size(); i++) {
				ProjectPhase projectPhase = projectPhaseList.get(i);
				List<ProjectPhaseCourse> courses = projectPhaseCourseService.listByProjectPhaseId(projectPhase.getId());
				if (courses != null && courses.size() > 0) {
					continue;
				} else {
					isAllPhaseCourseAssigned = false;
				}
			}
		}

		if (!isAllPhaseCourseAssigned) {
			project.setStatus("课程添加未完成");
			projectDataService.update(project);
			return;
		}

		int traineeCount = projectTraineeService.countByProjectId(project.getId());
		if (traineeCount < 1) {
			project.setStatus("学员添加未完成");
			projectDataService.update(project);
			return;
		}
		project.setStatus("正常");
		projectDataService.update(project);
		return;

	}

	/**
	 * 删除项目学员
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{projectTraineeId}/trainee-delete", method = RequestMethod.GET)
	@MenuSetting("submenu-project-data-management")
	public ModelAndView disableTrainee(@PathVariable("projectTraineeId") Long projectTraineeId) {

		ModelAndView modelAndView = new ModelAndView("project-data/project-data-trainee-delete");

		ProjectTrainee projectTrainee = projectTraineeService.load(ProjectTrainee.class, projectTraineeId);
		modelAndView.addObject("projectTrainee", projectTrainee);

		return modelAndView;
	}

	/**
	 * 删除项目学员提交
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{projectTraineeId}/trainee-delete", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-project-data-management")
	public @ResponseBody HttpResult onDisableTrainee(@PathVariable("projectTraineeId") Long projectTraineeId) {
		
	    HttpResult httpResult = new HttpResult();
		
		try {
		    
			ProjectTrainee projectTrainee = projectTraineeService.load(ProjectTrainee.class, projectTraineeId);
			projectTraineeService.update(projectTrainee.delete());

			updateProjectStatus(projectTrainee.getProject());
			httpResult.success().message("删除项目学员成功");

		} catch (Exception e) {
			httpResult.fail("500").message("删除项目学员失败! " + e.getMessage());
			logger.error("#onDisableTrainee() - delete project trainee fail, exception is [{}]", e);
		}

		return httpResult;

	}

	/**
	 * 添加学员查询条件输入
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{projectId}/trainee-search", method = RequestMethod.GET)
	@MenuSetting("submenu-project-data-management")
	public ModelAndView searchTrainee(@PathVariable("projectId") Long projectId) {

		ModelAndView modelAndView = new ModelAndView("project-data/project-data-trainee-search");

		Project project = projectDataService.load(Project.class, projectId);
		modelAndView.addObject("project", project);

		return modelAndView;
	}

	/**
	 * 批量导入学员
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{projectId}/trainee-upload", method = RequestMethod.GET)
	public ModelAndView upload(@PathVariable("projectId") Long projectId) {
		ModelAndView modelAndView = new ModelAndView("project-data/project-data-trainee-upload");
		modelAndView.addObject("projectId", projectId);
		return modelAndView;
	}

	/**
	 * 批量导入学员
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{projectId}/trainee-upload", method = RequestMethod.POST)
	public ModelAndView onUpload(@PathVariable("projectId") Long projectId, @RequestParam("file") MultipartFile file,
			RedirectAttributes attributes) {

		ModelAndView modelAndView = new ModelAndView("redirect:/project-data/" + projectId + "/detail");

		Project project = projectDataService.load(Project.class, projectId);
		Map<String, Object> result = projectTraineeService.createByFile(file, project);
		
		String filePath = (String) result.get("filePath");
			
		if(filePath != null) {
			modelAndView = new ModelAndView("redirect:/project-data/" + projectId + "/detail?filePath="+filePath);
		}
		
		return modelAndView;
	}
	

	/**
	 * 添加学员提交
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{projectId}/trainee-add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-project-data-management")
	public @ResponseBody HttpResult onAddTrainee(@RequestParam Long projectId, @RequestParam List<Long> selectTraineeIds) {

		HttpResult httpResult = new HttpResult();
		
		try {
			
		    Project project = projectDataService.load(Project.class, projectId);
			projectTraineeService.create(project, selectTraineeIds);
			
			httpResult.success().message("添加学员成功");

		} catch (Exception e) {
			httpResult.fail("500").message("添加学员失败! " + e.getMessage());
			logger.error("#onAddTrainee() - add trainee fail, exception is [{}]", e);
		}

		return httpResult;

	}
}
